<script>
import totalPackageContractApi from '@/api/legal/branchContract/totalPackageContract'

export default {
  name: 'ContractReviewBranch',
  props: {
    state: {
      type: Number,
      default() {
        return 1
      }
    },
    baseForm: {
      type: Object,
      default() {
        return {}
      }
    },
    type: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      table: [
        [
          {
            appointment: null,
            baseId: '660817662611427328',
            branchComReviewInfoId: '660817662724673538',
            code: '1001',
            control: null,
            enabled: 'FALSE',
            id: '660817662724673538',
            level: 3,
            name: '发包人资信：<br>建设行政审批手续是否齐全？是<input label="是"  type="checkbox"/>否<input type="checkbox"  label="否"/><br>发包主体是否具备法人资格？<br>工程招标人、中标通知书中的发包人与合同发包人是否一致？',
            riskPreventionLevel: null,
            riskPreventionMeasures: null,
            sortNum: 1,
            type: 'GENERAL_CONTRACT_TYPE'
          },
          {
            appointment: null,
            baseId: '660817662611427328',
            branchComReviewInfoId: '660817662728867842',
            code: '1001',
            control: null,
            enabled: 'FALSE',
            id: '660817662728867842',
            level: 2,
            name: '项目市场准入和投标审批通过？是<input label="是"  type="checkbox"/>否<input type="checkbox"  label="否"/>',
            riskPreventionLevel: null,
            riskPreventionMeasures: null,
            sortNum: 2,
            type: 'GENERAL_CONTRACT_TYPE'
          },
          {
            appointment: null,
            baseId: '660817662611427328',
            branchComReviewInfoId: '660817662737256448',
            code: '1001',
            control: null,
            enabled: 'FALSE',
            id: '660817662737256448',
            level: 3,
            name: '触碰局限制性或禁止性规定的内容',
            riskPreventionLevel: null,
            riskPreventionMeasures: null,
            sortNum: 3,
            type: 'GENERAL_CONTRACT_TYPE'
          },
          {
            appointment: null,
            baseId: '660817662611427328',
            branchComReviewInfoId: '660817662741450755',
            code: '1001',
            control: null,
            enabled: 'FALSE',
            id: '660817662741450755',
            level: 2,
            name: '与招投标文件的符合性或差异条款内容核实',
            riskPreventionLevel: null,
            riskPreventionMeasures: null,
            sortNum: 4,
            type: 'GENERAL_CONTRACT_TYPE'
          },
          {
            appointment: null,
            baseId: '660817662611427328',
            branchComReviewInfoId: '660817662749839361',
            code: '1001',
            control: null,
            enabled: 'FALSE',
            id: '660817662749839361',
            level: 3,
            name: '中标价格合理性？',
            riskPreventionLevel: null,
            riskPreventionMeasures: null,
            sortNum: 5,
            type: 'GENERAL_CONTRACT_TYPE'
          },
          {
            appointment: null,
            baseId: '660817662611427328',
            branchComReviewInfoId: '660817662754033665',
            code: '1001',
            control: null,
            enabled: 'FALSE',
            id: '660817662754033665',
            level: 3,
            name: '是否为特殊项目并经局审批？',
            riskPreventionLevel: null,
            riskPreventionMeasures: null,
            sortNum: 6,
            type: 'GENERAL_CONTRACT_TYPE'
          },
          {
            appointment: null,
            baseId: '660817662611427328',
            branchComReviewInfoId: '660817662758227969',
            code: '1001',
            control: null,
            enabled: 'FALSE',
            id: '660817662758227969',
            level: 2,
            name: '承包内容与范围与招标内容和范围是否一\\n致？',
            riskPreventionLevel: null,
            riskPreventionMeasures: null,
            sortNum: 7,
            type: 'GENERAL_CONTRACT_TYPE'
          },
          {
            appointment: null,
            baseId: '660817662611427328',
            branchComReviewInfoId: '660817662762422273',
            code: '1001',
            control: null,
            enabled: 'FALSE',
            id: '660817662762422273',
            level: 1,
            name: '其它与部门职能相关的条款',
            riskPreventionLevel: null,
            riskPreventionMeasures: null,
            sortNum: 8,
            type: 'GENERAL_CONTRACT_TYPE'
          },
          {
            appointment: null,
            baseId: '660817662611427328',
            branchComReviewInfoId: '660817662766616579',
            code: '1001',
            control: null,
            enabled: 'FALSE',
            id: '660817662766616579',
            level: 4,
            name: '本评审范围合同风险是否整体受控及建议措施',
            riskPreventionLevel: null,
            riskPreventionMeasures: null,
            sortNum: 9,
            type: 'GENERAL_CONTRACT_TYPE'
          },
          {
            appointment: null,
            baseId: '660817662611427328',
            branchComReviewInfoId: '660817662770810883',
            code: '1001',
            control: null,
            enabled: 'FALSE',
            id: '660817662770810883',
            level: 5,
            name: '部门负责人结论性意见',
            riskPreventionLevel: null,
            riskPreventionMeasures: null,
            sortNum: 10,
            type: 'GENERAL_CONTRACT_TYPE'
          }
        ]
      ],
      loading: false,
      isSubmit: false,
      status: this.state,
      // 流程监控查看
      monitoringDetail: this.$route.query.hasOwnProperty('isMonitoring') && !this.$route.query.hasOwnProperty('monitoringType')
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      let taskDefKey = this.$route.query.taskDefKey
      let code = []
      switch (taskDefKey) {
        case 'legal_general_branchcom_basic':
          code = [1001]
          break
        case 'legal_general_branchcom_project':
          code = [1002]
          break
        case 'legal_general_branchcom_finance':
          code = [1003]
          break
        case 'legal_general_branchcom_legal':
          code = [1004]
          break
        case 'legal_general_branchcom_business':
          code = [1005]
          break
        case 'legal_general_branchcom_science':
          code = [1006]
          break
        case 'legal_general_com_basic':
          code = [1001]
          break
        case 'legal_general_com_project':
          code = [1002]
          break
        case 'legal_general_com_finance':
          code = [1003]
          break
        case 'legal_general_com_legal':
          code = [1004]
          break
        case 'legal_general_com_business':
          code = [1005]
          break
        case 'legal_general_com_legal_adviser':
          code = [1006]
          break
        case 'legal_general_branchcom_economics':
          this.status = 3

        case 'legal_general_branchcom_manager':
          this.status = 3

        default:
          code = [1001, 1002, 1003, 1004, 1005, 1006]
          break
      }
      if (this.monitoringDetail) {
        this.status = 3
        code = [1001, 1002, 1003, 1004, 1005, 1006]
      }
      this.loading = true
      const api = ['findBranchComAuditInfoByBaseId', 'finComAuditInfoByBaseId']
      let res = await totalPackageContractApi[api[this.type === 'Branch' ? 0 : 1]]({
        modelCodes: code,
        pageNo: 1,
        pageSize: 10000,
        baseId: this.baseForm.baseId,
        edit: this.status !== 3
      })
      if (res.code === 200) {
        let list = res.data
        this.table = []
        Object.keys(list).map((key) => {
          list[key].map((value) => {
            value.name = value.name.replace(/\\n/g, '\n')
            if (value.control !== null) {
              value.isControl = value.control ? '1' : '0'
            } else {
              value.isControl = null
            }
          })
          this.table.push(list[key])
        })
        setTimeout(() => {
          if (this.status === 3) {
            let checkboxs = document.querySelectorAll('input[type="checkbox"]')
            checkboxs.forEach((v) => {
              v.setAttribute('disabled', true)
            })
          } else {
            let checkboxs = document.querySelectorAll('input[type="checkbox"]')
            checkboxs.forEach((v) => {
              v.addEventListener('change', (e) => {
                if (v.getAttribute('label') === '是') {
                  v.nextElementSibling.nextElementSibling.checked = false
                  v.nextElementSibling.nextElementSibling.removeAttribute('checked')
                }
                if (v.getAttribute('label') === '否') {
                  v.previousElementSibling.previousElementSibling.checked = false
                  v.previousElementSibling.previousElementSibling.removeAttribute('checked')
                }
                if (e.target.checked) {
                  v.setAttribute('checked', e.target.checked)
                } else {
                  v.removeAttribute('checked')
                }
              })
            })
          }
        }, 500)
      }
      this.loading = false
    },
    validateForm() {
      let res = true
      // let inputs = document.querySelectorAll('table textarea')
      // for (let i = 0; i < inputs.length; i++) {
      //   if (inputs[i].value === '') {
      //     res = false
      //     break
      //   }
      // }
      //第三列必选，并且如果是选的是是，那个第四列也必选
      let selects = document.querySelectorAll('.ant-select-selection__rendered .ant-select-selection-selected-value')
      //parentElement.parentElement.parentElement.parentElement.nextElementSibling.nextElementSibling.querySelector('textarea')
      for (let i = 0; i < selects.length; i++) {
        let item = selects[i]
        if (item.getAttribute('title') === '') {
          res = false
          break
        }
        if (item.getAttribute('title') === '否') {
          let textarea = item.parentElement.parentElement.parentElement.parentElement.parentElement.nextElementSibling.nextElementSibling.querySelector('textarea')
          if (textarea.value === '') {
            res = false
            break
          }
        }
      }

      let checkboxs = document.querySelectorAll('input[type="checkbox"]')
      checkboxs.forEach((v, i, a) => {
        if (i % 2 === 0) {
          if (v.getAttribute('checked') !== 'true') {
            if (v.nextElementSibling.nextElementSibling.getAttribute('checked') !== 'true') {
              res = false
            }
          }
        }
      })
      return res
    },
    async submit(status = 'save') {
      let data = this.$clone(this.table[0])
      data.map((v) => {
        let item = document.querySelector('#a' + v.id)
        v.name = item.innerHTML
      })

      if (!this.validateForm()) {
        return this.$noticeWarning('请先填写完整数据！')
      }
      this.loading = true
      this.$bus.$emit('loading')
      const api = ['editBranchComAuditInfoById', 'editComAuditInfoById']
      let res = await totalPackageContractApi[api[this.type === 'Branch' ? 0 : 1]](data)
      if (res.code === 200) {
        if (status == 'Approval') {
          this.$bus.$emit('handelApprovalCopy')
        } else {
          this.$noticeSuccess('保存成功')
          this.$bus.$emit('unloading')
        }
      }
      this.loading = false
    }
  },
  mounted() {
    // this.$bus.$on('handelUnApproval', () => {
    //     if (this.validateForm()) {
    //         this.$bus.$emit('handelUnApprovalCopy')
    //     }
    // })
    this.$bus.$on('handelApproval', () => {
      if (this.status == 3) {
        this.$bus.$emit('handelApprovalCopy')
      } else {
        // if (!this.isSubmit) {
        this.submit('Approval')
        // this.$noticeWarning('请先保存数据')
        // return false
        // } else {
        //     this.$bus.$emit('handelApprovalCopy')
        // }
      }
    })
  },
  // 合同评审（公司）
  destroyed() {
    this.$bus.$off('handelApproval')
  },
  render(createElement, context) {
    return (
      <a-spin spinning={this.loading}>
        <a-card>
          <title-name title={this.type == 'Branch' ? '合同评审（分公司）' : '合同评审（公司）'}></title-name>
          <table>
            <thead>
              <tr>
                <th>评审部门</th>
                <th width="30%">评审内容</th>
                <th>合同约定</th>
                <th>风险是否受控</th>
                <th>风险控制级别</th>
                <th>风险防控措施</th>
              </tr>
            </thead>
            {this.table.map((key, keyIndex, keyArray) => {
              // <pre>{value.name}</pre>
              return (
                <tbody>
                  {key.map((value, index, array) => {
                    return (
                      <tr>
                        {index === 0 ? <td rowSpan={array.length}>{value.codeName}</td> : ''}
                        <td width="30%">
                          <div id={'a' + value.id} domPropsInnerHTML={value.name}></div>
                        </td>
                        {[1, 2, 3].findIndex((value1) => value1 === value.level) !== -1 ? (
                          <td>
                            {this.status !== 3 ? (
                              <BaseTextarea
                                class="requiredFormItem"
                                type="text"
                                value={value.appointment}
                                onInput={(e) => {
                                  value.appointment = e.target.value
                                }}
                              />
                            ) : (
                              value.appointment
                            )}
                          </td>
                        ) : (
                          ''
                        )}
                        {[1, 2, 3].findIndex((value1) => value1 === value.level) !== -1 ? (
                          <td align="center">
                            <span class="requiredFormItem">
                              {this.status !== 3 ? (
                                <a-select
                                  class=""
                                  style="width:80px;"
                                  placeholder={'请选择'}
                                  value={value.isControl}
                                  onChange={(e) => {
                                    value.isControl = e
                                  }}
                                >
                                  <a-select-option value="1">是</a-select-option>
                                  <a-select-option value="0">否</a-select-option>
                                </a-select>
                              ) : value.isControl ? (
                                value.isControl === '1' ? (
                                  '是'
                                ) : (
                                  '否'
                                )
                              ) : (
                                ''
                              )}
                            </span>
                          </td>
                        ) : (
                          ''
                        )}
                        {[1, 2, 3].findIndex((value1) => value1 === value.level) !== -1 ? (
                          <td
                            align="center"
                            style={{
                              background: value.level === 1 ? 'blue' : value.level === 2 ? 'yellow' : 'red'
                            }}
                          >
                            {value.level === 1 ? '蓝' : value.level === 2 ? '黄' : '红'}
                          </td>
                        ) : (
                          ''
                        )}
                        {[1, 2, 3].findIndex((value1) => value1 === value.level) !== -1 ? (
                          <td>
                            {this.status !== 3 ? (
                              <BaseTextarea
                                type="text"
                                value={value.riskPreventionMeasures}
                                onInput={(e) => {
                                  value.riskPreventionMeasures = e.target.value
                                }}
                              />
                            ) : (
                              value.riskPreventionMeasures
                            )}
                          </td>
                        ) : (
                          ''
                        )}
                        {[4, 5].findIndex((value1) => value1 === value.level) !== -1 ? (
                          <td colSpan="4">
                            {this.status !== 3 ? (
                              <BaseTextarea
                                type="text"
                                value={value.appointment}
                                onInput={(e) => {
                                  value.appointment = e.target.value
                                }}
                              />
                            ) : (
                              value.appointment
                            )}
                          </td>
                        ) : (
                          ''
                        )}
                      </tr>
                    )
                  })}
                </tbody>
              )
            })}
          </table>
        </a-card>
        {this.status !== 3 && (
          <div class="operation page-btn-right-top" style="right: 132px;">
            <a-button type="primary" onClick={this.submit} style="margin-right: 10px">
              保存
            </a-button>
          </div>
        )}
      </a-spin>
    )
  }
}
</script>

<style lang="less" scoped>
table {
  width: 100%;
  border: 1px solid gainsboro;

  thead {
    background: rgb(244, 244, 244);

    th {
      padding: 10px;
      border: 1px solid gainsboro;
    }
  }

  tbody {
    td {
      padding: 10px;
      border: 1px solid gainsboro;
    }
  }
}

.btn {
  position: absolute;
  right: 100px;
}
</style>
